export class LunarCalendar {
  static convertSolarToLunar(solar: Date) {
    // 阳历日期对象
    // const solar = new Date(solarDate);

    // 阴历年份
    let lunarYear = solar.getFullYear();
    let lunarMonth = 0;
    let lunarDay = 0;

    // 阴历月份的天数数组
    const lunarMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    // 判断是否为闰年
    let isLeap = false;
    if ((lunarYear % 4 === 0 && lunarYear % 100!== 0) || lunarYear % 400 === 0) {
      isLeap = true;
    }

    // 检查阴历年份是否在有效范围内
    if (lunarYear < 1900 || lunarYear > (new Date()).getFullYear()) {
      throw new Error('Invalid lunar year. Please ensure the year is within the valid range.');
    }

    // 计算阴历月份和日期
    for (let i = 1900; i < solar.getFullYear(); i++) {
      if (isLeap) {
        if (lunarMonth < lunarMonthDays[i]) {
          lunarMonth++;
        } else {
          lunarMonth = 1;
          if (i % 4 === 0 && i % 100!== 0) {
            lunarDay++;
          }
        }
      } else {
        if (lunarMonth < lunarMonthDays[i]) {
          lunarMonth++;
        }
      }
    }

    for (let i = 1; i < solar.getMonth() + 1; i++) {
      if (isLeap && i === 2) {
        if (lunarMonth < lunarMonthDays[lunarYear]) {
          lunarMonth++;
        }
      } else if (lunarMonth < lunarMonthDays[lunarYear]) {
        lunarMonth++;
      }
    }

    if (isLeap && lunarMonth === 2 && solar.getDate() > lunarMonthDays[lunarYear]) {
      lunarDay = 1;
    } else if (lunarMonth === lunarMonthDays[lunarYear]) {
      lunarDay = solar.getDate();
    } else {
      lunarDay = lunarMonthDays[lunarYear] - solar.getDate() + 1;
    }

    // 返回阴历日期对象
    return { year: lunarYear, month: lunarMonth, day: lunarDay, isLeap: isLeap };
  }

  // // 示例用法
  // const solarDate = new Date('2023-05-01');
  // const lunarDate = convertSolarToLunar(solarDate);
  // console.log('阴历日期:', lunarDate);
}